package com.rf.richfitwheel.admin.sys.controller;

import com.rf.richfitwheel.admin.annotation.UserOperateLog;
import com.rf.richfitwheel.admin.contants.UrlConstant;
import com.rf.richfitwheel.admin.sys.model.*;
import com.rf.richfitwheel.admin.sys.service.OrgService;
import com.rf.richfitwheel.admin.sys.service.SysUserMngOrgService;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.common.utils.TreeUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 机构管理
 * redisTemplate
 *
 * @author hushouquan
 */
@RestController
@RequestMapping(UrlConstant.WEB_ADMIN_URL + "/org")
public class SysOrgController {

    private static Logger log = LoggerFactory.getLogger(SysOrgController.class);

    @Autowired
    private OrgService orgService;
    @Autowired
    private SysUserMngOrgService sysUserMngOrgService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据id删除机构
     *
     * @return
     */
    @PostMapping("/getOrgVOById")
    public R getOrgVOById(@RequestBody String id) {
        OrgVO orgVO = this.orgService.getOrgVOById(id);
        return R.ok().put("orgVO", orgVO);
    }

    /**
     * 获取树形机构
     *
     * @param org 所在机构id
     * @return
     * @throws Exception
     */
//    @RequestMapping("/treeList")
//    @ResponseBody
//    public List<TreeUtils> treeListByParam(@RequestBody Org org) throws Exception {
//        User user = UserUtil.getUser();
//        if (Constant.ADMIN.equals(user.getUsername())) {
//            return orgService.getAllOrgTreeUtils();
//        } else { //不是超管，只能查看本单位下的
//            return orgService.getAllOrgTreeUtils();
////			return orgService.getAllOrgTreeUtilsByParam(org);
//        }
//    }

    /**
     * 获取树形机构 包括部门
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/treeListIncludeDeptByParentId/{parentId}")
    @ResponseBody
    public List<TreeUtils> treeListIncludeDeptByParentId(@PathVariable("parentId") String parentId) throws Exception {
//        if (StringUtils.isBlank(parentId)) {
//            return new ArrayList<TreeUtils>();
//        }
        UserVO userVO = UserUtil.getUser();
        if (userVO.getUsername().equals(Constant.ADMIN)) {//超管
            parentId = "".equals(parentId) ? "0" : parentId;
            return orgService.getOrgsTreeUtilsIncludeDeptByParentId(parentId);
        } else if (!userVO.getUsername().equals(Constant.ADMIN) && "0".equals(parentId)) {//不是超管，先查询出所在机构
            if(Constant.OrgRank.ORGRANK_DEPT.getValue().equals(userVO.getDefaultOrg().getOrgRank())){
                //如果是部门
                if(Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getParentOrg().getOrgType())){
                    //上级如果是虚拟机构（本部）则找爷爷
                    return orgService.getOrgsTreeUtilsIncludeDeptById(userVO.getDefaultOrg().getGrandpa().getId());
                }else{
                    //上级如果是实体
                    return orgService.getOrgsTreeUtilsIncludeDeptById(userVO.getDefaultOrg().getParentOrg().getId());
                }
            }else{
                if(Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getOrgType())){
                    //如果是虚拟机构（本部）则找爸爸
                    return orgService.getOrgsTreeUtilsIncludeDeptById(userVO.getDefaultOrg().getParentOrg().getId());
                }else{
                    //上级如果是实体
                    return orgService.getOrgsTreeUtilsIncludeDeptById(userVO.getDefaultOrg().getId());
                }
            }
        } else { //非超管的下一级机构或部门
            return orgService.getOrgsTreeUtilsIncludeDeptByParentId(parentId);
        }

    }

    /**
     * @param id 登陆人所在机构(不是部门)id（不是部门id）
     * @功能描述: 根据当前登录用户所在的机构
     * @auther: jiaozhongcai
     * @return: List<TreeUtils>
     */
    @RequestMapping("/treeListIncludeDeptById/{id}")
    @ResponseBody
    public List<TreeUtils> treeListIncludeDeptById(@PathVariable("id") String id) throws Exception {
        if (StringUtils.isBlank(id)) {
            return new ArrayList<TreeUtils>();
        }
        return orgService.getOrgsTreeUtilsIncludeDeptById(id);
    }


    /**
     * 获取树形机构 包括部门
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/treeListIncludeDeptByParentId1")
    @ResponseBody
    public List<TreeUtils> treeListIncludeDeptByParentId1(@RequestBody TreeUtils treeUtils) throws Exception {
        if (StringUtils.isBlank(treeUtils.getId())) {
            treeUtils.setId("0");
        }
        return orgService.getOrgsTreeUtilsIncludeDeptByParentId(treeUtils.getId());
    }

    /**
     * 获取树形机构 排除部门
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/treeListExcludeDeptByParentId1")
    @ResponseBody
    public List<TreeUtils> treeListExcludeDeptByParentId1(@RequestBody TreeUtils treeUtils) throws Exception {
        if (StringUtils.isBlank(treeUtils.getId())) {
            treeUtils.setId("0");
        }
        return orgService.getOrgsTreeUtilsExcludeDeptByParentId(treeUtils.getId());
    }

    /**
     * 获取树形机构 排除部门
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/treeListExcludeDeptByParentId/{parentId}")
    @ResponseBody
    public List<TreeUtils> treeListExcludeDeptByParentId(@PathVariable("parentId") String parentId) throws Exception {
        /*if (StringUtils.isBlank(parentId)) {
            return new ArrayList<TreeUtils>();
        }*/
        UserVO userVO = UserUtil.getUser();
        if (userVO.getUsername().equals(Constant.ADMIN)) {//超管
            parentId = "".equals(parentId) ? "0" : parentId;
            return orgService.getOrgsTreeUtilsExcludeDeptByParentId(parentId);
        } else if (!userVO.getUsername().equals(Constant.ADMIN) && "0".equals(parentId)) {//不是超管，先查询出所在机构
            if(Constant.OrgRank.ORGRANK_DEPT.getValue().equals(userVO.getDefaultOrg().getOrgRank())){
                //如果是部门
                if(Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getParentOrg().getOrgType())){
                    //上级如果是虚拟机构（本部）则找爷爷
                    return orgService.getOrgsTreeUtilsExcludeDeptById(userVO.getDefaultOrg().getGrandpa().getId());
                }else{
                    //上级如果是实体
                    return orgService.getOrgsTreeUtilsExcludeDeptById(userVO.getDefaultOrg().getParentOrg().getId());
                }
            }else{
                if(Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getOrgType())){
                    //如果是虚拟机构（本部）则找爸爸
                    return orgService.getOrgsTreeUtilsExcludeDeptById(userVO.getDefaultOrg().getParentOrg().getId());
                }else{
                    //上级如果是实体
                    return orgService.getOrgsTreeUtilsExcludeDeptById(userVO.getDefaultOrg().getId());
                }
            }
        } else { //非超管的下一级机构或部门
            return orgService.getOrgsTreeUtilsExcludeDeptByParentId(parentId);
        }

//        return orgService.getOrgsTreeUtilsExcludeDeptByParentId(parentId);
    }

    /**
     * 获取树形机构
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/treeList/{tenantId}")
    @ResponseBody
    public List<TreeUtils> treeList(@PathVariable("tenantId") String tenantId) throws Exception {
        if (StringUtils.isBlank(tenantId)) {
            return new ArrayList<TreeUtils>();
        }
        return orgService.getAllOrgTreeUtils(tenantId);
    }

    /**
     * @param
     * @功能描述: 获取当前登录人所属部门和机构信息, 用户必须在某个部门下,有问题别用
     * 格式:  机构id-机构编码-机构名称-部门id-部门编码-部门名称
     * @auther: jiaozhongcai
     * @return: List<OrgVO>
     */
    @RequestMapping("/getSelfAndParentOrgInfo")
    @ResponseBody
    public R getSelfAndParentOrgInfo() {
        UserVO userVO = UserUtil.getUser();
        List<OrgVO> selfOrgList = userVO.getMngOrgs();
        return R.ok().put("selfOrgList", selfOrgList);
    }


    /**
     * 保存机构数据
     *
     * @param org
     * @return
     */
    @UserOperateLog(module = "系统功能", methods = "save", description = "新增或修改机构信息")
    @PostMapping("/save")
    public R save(@RequestBody Org org) {
        try {
            if (org.getId() == null || "".equals(org.getId())) {
                //新增
                orgService.addOrg(org, UserUtil.getUser());
            } else {
                //修改
                orgService.updateOrg(org, UserUtil.getUser());
            }
            return R.ok();
        } catch (BusinessException e){
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("保存机构信息失败", e);
            return R.error("保存机构信息失败");
        }
    }

    /**
     * 根据id删除机构
     *
     * @return
     */
    @UserOperateLog(module = "系统功能", methods = "deleteById", description = "删除机构信息")
    @PostMapping("/deleteById")
    public R deleteById(@RequestBody String id) {
        orgService.deleteById(id, UserUtil.getUser());
        return R.ok();
    }

    /**
     * @param
     * @功能描述: 获取当前登录人所属企业及上级企业信息
     * @auther: 田炜俊
     * @return: EntAndUpperEntVo
     */
    @GetMapping("/getEntAndUpperEntInfo")
    public R getEntAndUpperEntInfo() {
        UserVO userVO = UserUtil.getUser();
        EntAndUpperEntVo entAndUpperEntVo = orgService.getEntAndUpperEntInfo(userVO);
        return R.ok().put("entAndUpperEntVo", entAndUpperEntVo);
    }

    /**
     * @param
     * @功能描述: 获取企业信息
     * @auther: 田炜俊
     * @return: EntAndUpperEntVo
     */
    @PostMapping("/queryPageEntInfoList")
    public R queryPageEntInfoList(@RequestBody Map<String, Object> params) {
        PageUtils page = orgService.queryPageEntInfoList(params);
        return R.ok().put("page", page);
    }

    /**
     * @param
     * @功能描述: 授信获取机构信息
     * @auther: 张鲁
     * @return: page
     */
    @PostMapping("/queryPageOrgByQueryType")
    public R queryPageOrgByQueryType(@RequestBody Map<String, Object> params) {
        String queryType = params.get("queryType").toString();
        if (queryType.equals("1")) {//获取所属一级机构及所有下级机构信息
            PageUtils page = orgService.queryPageGradeOneAndChildOrg(params, UserUtil.getUser());
            return R.ok().put("page", page);
        } else if (queryType.equals("2")) {//获取当前机构及下级所有机构信息
            PageUtils page = orgService.queryPageOrgAndChildOrg(params, UserUtil.getUser());
            return R.ok().put("page", page);
        } else if (queryType.equals("3")) {//股份或者集团下一级机构
            PageUtils page = orgService.queryPageGradeOneOrg(params, UserUtil.getUser());
            return R.ok().put("page", page);
        }else if (queryType.equals("4")) {//查询全部的公司单位信息
            PageUtils page = orgService.queryOneOrgAll(params, UserUtil.getUser());
            return R.ok().put("page", page);
        }else if (queryType.equals("9")) {//不分页查询当前和下级所有非本部机构信息
            List<Org> orgs = orgService.queryOneOrgList(params, UserUtil.getUser());
            return R.ok().put("orgs", orgs);
        }
        return R.ok();
    }

    /**
     * @param
     * @功能描述: 债务融资查询机构数据
     * @auther: 张鲁
     * @return: page
     */
    @PostMapping("/DeptqueryOrgByQueryType")
    public R queryPageOrgByQueryTypeDept(@RequestBody Map<String, Object> params) {
        List<Org> orgList=orgService.queryOneOrgAllList(params, UserUtil.getUser());
        return R.ok().put("page", orgList);
    }
    /**
     * @param
     * @功能描述:根据传入的单位编号查找上级单位直到最顶级
     * @return: params
     */
    @PostMapping("/findOrgUpList")
    public R findOrgUpList(@RequestBody Map<String, Object>  params) {
        List<Org> orgList=orgService.findOrgUpList(params);
        return R.ok().put("orgList", orgList);
    }
    /**
     * @param
     * @功能描述:根据单位编码查询本单位下的部门信息
     * @return: params
     */
    @PostMapping("/findOrgDeptList")
    public R findOrgDeptList(@RequestBody Map<String, Object>  params) {
        List<Org> orgList=orgService.findOrgDeptList(params);
        return R.ok().put("orgList", orgList);
    }
    /**
     * @param
     * @功能描述:根据单位编码查询单个org信息
     * @return: params
     */
    @PostMapping("/getOrgByOrgCode")
    public R getOrgByOrgCode(@RequestBody Map<String, Object>  params) {
        String orgCode = String.valueOf(params.get("orgCode"));
        Org org=orgService.getOrgByOrgCode(orgCode);
        return R.ok().put("org", org);
    }
    /**
     * @param
     * @功能描述:根据单位编码查询单位下一级的机构
     * @return: params
     */
    @PostMapping("/getOrgByOrgCodeAll")
    public R getOrgByOrgCodeAll(@RequestBody Map<String, Object>  params) {
        String orgCode = String.valueOf(params.get("orgCode"));
        List<Org> orgs=orgService.getOrgByOrgCodeAll(orgCode);
        return R.ok().put("org", orgs);
    }

    /**
     * @param
     * @功能描述:根据单位编码查询单位下所有的机构
     * @return: params
     */
    @PostMapping("/getOrgByOrgCodeDownAll")
    public R getOrgByOrgCodeDownAll(@RequestBody Map<String, Object>  params) {
        String orgCode = String.valueOf(params.get("orgCode"));
        List<Org> orgs=orgService.getOrgByOrgCodeDownAll(orgCode);
        return R.ok().put("org", orgs);
    }
    /**
     * @param
     * @功能描述:根据单位编码查询下一级单位的数据 返回每一组的数据
     * @return: params
     */
    @PostMapping("/findOrgList")
    public  HashMap<String, List<Org>> findOrgList(@RequestBody Map<String, Object>  params) {
        String orgCode = String.valueOf(params.get("orgCode"));
        HashMap<String, List<Org>>listHashMap=orgService.findOrgList(orgCode);
        return listHashMap;
    }

    /**
     *
     * @功能描述:根据单位编码查询单个org信息
     * @param orgId String
     * @return
     */
    @PostMapping("/getOrgById")
    public Org getOrgById(@RequestBody String orgId) {
        return orgService.selectById(orgId);
    }

    /**
     *
     * @功能描述:根据单位编码查询单个org信息
     * @param orgCode String
     * @return
     */
    @PostMapping("/getOrgByCode")
    public Org getOrgByCode(@RequestBody String orgCode) {
        return orgService.selectByOrgCode(orgCode);
    }

    /**
     * @param
     * @功能描述: 获取当前登录人及其下属各级企业编码
     * @auther: 田炜俊
     * @return: List<String>
     */
    @GetMapping("/getCurrentAndChildrenEntCodeList")
    public R getCurrentAndChildrenEntCodeList() {
        UserVO userVO = UserUtil.getUser();
        Set<String> set = orgService.getCurrentAndChildrenEntCodeList(userVO);
        return R.ok().put("set", set);
    }


    @PostMapping("/getOrgListByParams")
    public R getOrgListByParams(@RequestBody Map<String, Object> params) {
        List<Org> list = orgService.getOrgListByParams(params);
        return R.ok().put("list", list);
    }

    @PostMapping("/getOrgListByOrgName")
    public R getOrgListByOrgName(@RequestBody Map<String, String> params) {
        List<Org> list = orgService.getOrgListByOrgName(params);
        return R.ok().put("list", list);
    }


    /**
     * 当前管理机构的树，包含当前所管的及下属所有非删除机构
     * @param params parentId
     *               orgRank
     *               isAllOrg
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/getOrgsTreeUtilsIncludeByParams")
    public List<TreeUtils> getOrgsTreeUtilsIncludeByParams(@RequestBody Map<String, Object> params) throws Exception {
        return orgService.getOrgsTreeUtilsIncludeByParams(params);
    }

    @GetMapping("/getOrgListByOrgCode/{orgCode}")
    public R getOrgListByOrgCode(@PathVariable("orgCode") String orgCode) {
        List<Org> list = orgService.getOrgListByOrgCode(orgCode);
        return R.ok().put("list", list);
    }

    @GetMapping("/getOrgListByOrgName2/{orgName}")
    public R getOrgListByOrgName2(@PathVariable("orgName") String orgName) {
        Map<String, String> params = new HashMap<>();
        params.put("orgName", orgName);
        List<Org> list = orgService.getOrgListByOrgName2(params);
        return R.ok().put("list", list);
    }

    /**
     * 当前管辖机构
     * @param userId
     * @return
     */
    @GetMapping("/queryUserMngOrgs/{userId}")
    public R queryUserMngOrgs(@PathVariable("userId") String userId) {
        List<UserMngOrg> list = sysUserMngOrgService.getListByUserId(userId);
        List<Map<String,Object>> listRe = list.stream().map(m -> {
            Map<String,Object> map = new HashMap<>();
            map.put("id", m.getId());
            map.put("userId", m.getUserId());
            Org org = orgService.selectById(m.getOrgId());
            map.put("orgId", m.getUserId());
            map.put("orgName", org.getOrgName());
            map.put("defaultState", m.getDefaultState());
            return map;
        }).collect(Collectors.toList());
//        List<Org> list = orgService.getOrgListByOrgCode(userId);
        return R.ok().put("list", listRe);
    }


    /**
     * 根据企业编号获取本级和下级企业信息
     *
     * @param params
     * @return
     */
    @PostMapping("/getOrgAndLowerOrgInfoByOrgCode")
    public R getOrgAndLowerOrgInfoByOrgCode(@RequestBody Map<String, Object> params) {
        try {
            List<Map<String, Object>> mapList = orgService.getOrgAndLowerOrgInfoByOrgCode(params);
            return R.ok().put("list", mapList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取失败", e);
            return R.error("获取失败");
        }
    }

    /**
     * 根据企业编号获取本级和下级企业信息 List<String>
     *
     * @param params
     * @return
     */
    @PostMapping("/getCurrentAndBelowOrgCodeListByOrgCode")
    public R getCurrentAndBelowOrgCodeListByOrgCode(@RequestBody Map<String, Object> params) {
        try {
            String orgCode = (String) params.get("orgCode");
            List<String> orgCodes = orgService.getCurrentAndBelowOrgCodeListByOrgCode(orgCode);
            return R.ok().put("orgCodes", orgCodes);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取失败", e);
            return R.error("获取失败");
        }
    }

    /**
     * 获取一级企业 授信专用
     *
     * @param params
     * @return
     */
    @PostMapping("/getGradeOneOrgCode")
    public R getGradeOneOrgCode(@RequestBody Map<String, Object> params) {
        try {
            String orgCode = (String) params.get("orgCode");
            Org org = orgService.getGradeOneOrgByOrgCode(orgCode);
            return R.ok().put("orgCode", org.getOrgCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取失败", e);
            return R.error("获取失败");
        }
    }

    /**
     * 获取树形机构 包括部门，admin是全量的，其他用户是当前管理机构的树
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/treeListIncludeDeptByParentIdDsb/{parentId}")
    @ResponseBody
    public List<OrgHasChildren> treeListIncludeDeptByParentIdDsb(@PathVariable("parentId") String parentId) throws Exception {
//        if (StringUtils.isBlank(parentId)) {
//            return new ArrayList<TreeUtils>();
//        }
        UserVO userVO = UserUtil.getUser();
        if (userVO.getUsername().equals(Constant.ADMIN)) {//超管
            parentId = "".equals(parentId) ? "0" : parentId;
            Org org = new Org();
            org.setParentId(parentId);
            return orgService.selectHashChildrenExcludeDept(org);
        } else {//不是超管，先查询出所在机构(当前管理的机构）
            Org org = new Org();
            if(Constant.OrgRank.ORGRANK_DEPT.getValue().equals(userVO.getDefaultOrg().getOrgRank())){
                //如果是部门
                if(Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getParentOrg().getOrgType())){
                    //上级如果是虚拟机构（本部）则找爷爷
                    org.setId(userVO.getDefaultOrg().getGrandpa().getId());
                }else{
                    //上级如果是实体
                    org.setId(userVO.getDefaultOrg().getParentOrg().getId());
                }
            }else{
                if(Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getOrgType())){
                    //如果是虚拟机构（本部）则找爸爸
                    org.setId(userVO.getDefaultOrg().getParentOrg().getId());
                }else{
                    //上级如果是实体
                    org.setId(userVO.getDefaultOrg().getId());
                }
            }
            return orgService.selectHashChildrenExcludeDept(org);
        }

    }

    /**
     * 根据id查询机构树，传入id及下级所有数据
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/treeListIncludeDeptByIdDsb/{id}")
    @ResponseBody
    public List<OrgHasChildren> treeListIncludeDeptByIdDsb(@PathVariable("id") String id) throws Exception {
        Org org = new Org();
        org.setId(id);
        return orgService.selectHashChildrenExcludeDept(org);
    }

    /**
     * 查询当前管理的机构，不包含部门,此方法性能较差，慎用
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/treeListexcludeDeptByIdDsb")
    @ResponseBody
    public List<OrgHasChildren> treeListexcludeDeptByIdDsb() throws Exception {
        UserVO userVO = UserUtil.getUser();
        Org org = new Org();
        if(Constant.OrgRank.ORGRANK_DEPT.getValue().equals(userVO.getDefaultOrg().getOrgRank())){
            //如果是部门
            if(Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getParentOrg().getOrgType())){
                //上级如果是虚拟机构（本部）则找爷爷
                org.setId(userVO.getDefaultOrg().getGrandpa().getId());
            }else{
                //上级如果是实体
                org.setId(userVO.getDefaultOrg().getParentOrg().getId());
            }
        }else{
            if(Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getOrgType())){
                //如果是虚拟机构（本部）则找爸爸
                org.setId(userVO.getDefaultOrg().getParentOrg().getId());
            }else{
                //上级如果是实体
                org.setId(userVO.getDefaultOrg().getId());
            }
        }
        org.setOrgRank(Constant.OrgRank.ORGRANK_COMPANY.getValue());
//        return orgService.selectByExampleHashChildrenExcludeDept(org);
        return orgService.selectHashChildrenExcludeDept(org);
    }

    /**
     * 查询当前管理的机构，不包含部门-内存处理机构层级
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/treeListExcludeDept")
    @ResponseBody
    public List<OrgHasChildren> treeListExcludeDept() throws Exception {
        Map<String,Object> param=new HashedMap();
        UserVO userVO = UserUtil.getUser();
        String mainId="";
        if(Constant.OrgRank.ORGRANK_DEPT.getValue().equals(userVO.getDefaultOrg().getOrgRank())){
            //如果是部门
            if(Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getParentOrg().getOrgType())){
                //上级如果是虚拟机构（本部）则找爷爷
                mainId=userVO.getDefaultOrg().getGrandpa().getId();
            }else{
                //上级如果是实体
                mainId=userVO.getDefaultOrg().getParentOrg().getId();
            }
        }else{
            if(Constant.OrgType.ORGRANK_VIRTUAL.getValue().equals(userVO.getDefaultOrg().getOrgType())){
                //如果是虚拟机构（本部）则找爸爸
                mainId=userVO.getDefaultOrg().getParentOrg().getId();
            }else{
                //上级如果是实体
                mainId=userVO.getDefaultOrg().getId();
            }
        }
        param.put("mainId",mainId);
        return orgService.selectAllOrgsByMainId(param);
    }

    /**
     * 查询当前管理的机构，不包含部门-内存处理机构层级
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/treeListExcludeDeptByMainId")
    @ResponseBody
    public List<OrgHasChildren> treeListExcludeDeptByMainId() throws Exception {
        Map<String,Object> param=new HashedMap();
        param.put("creditCode","91110000710935732K");
        return orgService.selectAllOrgsByMainId(param);
    }

    @GetMapping(value = "/queryDeptByParentId/{id}")
    public List<Org> queryDeptByParentId(@PathVariable("id") String id){
        return orgService.queryDeptByParentId(id);
    }

    @PostMapping(value = "/queryDeptByParentIdAndName")
    public List<Org> queryDeptByParentIdAndName(@RequestBody Map<String, Object> params){
        return orgService.queryDeptByParentIdAndName(params);
    }

    /**
     * 根据机构id查询所有直接下级机构（不包含部门）
     * @param id
     * @return
     */
    @GetMapping(value = "/queryOrgsExcludeDeptByParentId/{id}")
    public List<Org> queryOrgsExcludeDeptByParentId(@PathVariable("id") String id){
        return orgService.queryOrgsByParentId(id, false);
    }

    /**
     * 根据机构id查询所有直接下级机构（包含部门）
     * @param id
     * @return
     */
    @GetMapping(value = "/queryOrgsIncludeDeptByParentId/{id}")
    public List<Org> queryOrgsIncludeDeptByParentId(@PathVariable("id") String id){
        return orgService.queryOrgsByParentId(id, true);
    }

    /**
     * 获取下一级单位所有部门信息
     * @param id
     * @return
     */
    @GetMapping("/querySonDeptListByParentOrgId/{id}")
    public List<Map<String,Object>> querySonDeptListByParentOrgId(@PathVariable("id") String id){
        try{
            return orgService.querySonDeptListByParentOrgId(id);
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询失败",e);
            return null;
        }
    }


    /**
     *  应收账款项目
     * 当前登录用户所属机构id，查其下属的所有公司
     * @param orgId String
     */
    @PostMapping("/getSubOrgByParentId")
    public List<Org> querySubOrgByParentId(@RequestBody String orgId) {

        final List<Org> orgs = orgService.queryOrgsByParentId(orgId, false);

        return orgs;
    }

    /**
     * 根据机构id查询所有下级机构,非树形
     * @param id
     * @param rank 1不包含部门
     * @return
     */
    @GetMapping(value = "/queryOrgsListExcludeDeptByParentId/{id}/{rank}")
    public List<OrgHasChildren> queryOrgsListExcludeDeptByParentId(@PathVariable("id") String id, @PathVariable("rank") String rank){
        Org org = new Org();
        org.setId(id);
        org.setOrgRank(rank);
        List<OrgHasChildren> list = orgService.queryOrgsListExcludeDeptByParentId(org);
        /*if("1".equals(rank)){
            org.setOrgRank(Constant.OrgRank.ORGRANK_COMPANY.getValue());
            List<OrgHasChildren> listTree = orgService.selectByExampleHashChildrenExcludeDept(org);
            return tree2List(listTree);
        }else{
            List<OrgHasChildren> listTree = orgService.selectByExampleHashChildren(org);
            return tree2List(listTree);
        }*/
        return list;
    }

    public static List<OrgHasChildren> tree2List(List<OrgHasChildren>  treeList) {
        List<OrgHasChildren> list = new ArrayList<>();
        for (OrgHasChildren tree : treeList) {
            List<OrgHasChildren> child = tree.getChildren();
            list.add(tree);
            if (child != null && child.size() > 0) {
                list.addAll(tree2List(child));
                tree.setChildren(null);
            }
        }
        return list;
    }

    /**
     * 机构迁移
     * @param org
     * @return
     */
    @UserOperateLog(module = "系统功能", methods = "save", description = "机构迁移")
    @PostMapping("/changeParent")
    public R changeParent(@RequestBody Org org) {
        try {
            if(StringUtils.isBlank(org.getParentId())){
                return R.error("请选择一个上级机构");
            }
            orgService.changeParent(org, UserUtil.getUser());
            return R.ok();
        } catch (BusinessException e){
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("保存机构信息失败", e);
            return R.error("保存机构信息失败");
        }
    }

    /**
     * 用户所有管辖单位
     * @param params 查询条件{page,limit,dataForm:{orgCode,orgName}}
     * @return
     */
    @PostMapping("/queryMngListIncludeDept")
    public R queryMngListIncludeDept(@RequestBody Map<String, Object> params) {
        UserVO user = UserUtil.getUser();
        List<String> mngIds = user.getMngOrgs().stream().map(Org::getId).collect(Collectors.toList());
        PageUtils page = orgService.queryMngListIncludeDept(params, mngIds);
        return R.ok().put("page", page);
    }

    /**
     * 获取所有机构list
     * @return
     */
    @PostMapping("/getAllOrgCompany")
    public List<Org> getAllOrgCompany() {
        return orgService.getAllOrgCompany();
    }

    /**
     * 根据orgCode查询机构
     *
     * @return
     */
    @PostMapping("/getOrgVOByOrgCode")
    public R getOrgVOByOrgCode(@RequestBody String orgCode) {
        OrgVO orgVO = orgService.getOrgAndParentOrgByOrgCode(orgCode);
        return R.ok().put("orgVO", orgVO);
    }
    
    /**
     * 根据orgCode查询机构,直接返回对象
     * @param orgCode 机构编号
     * @return
     */
    @PostMapping("/getOrgVOObjectByOrgCode")
    public OrgVO getOrgVOObjectByOrgCode(@RequestBody String orgCode) {
        return orgService.getOrgAndParentOrgByOrgCode(orgCode);
    }
    
    /**
     * 向上查询直至顶级
     * @param orgIds
     * @return
     */
    @PostMapping("/getOrgListByOrgIdUpHasSelf")
    public R getOrgListByOrgIdUpHasSelf(@RequestBody String[] orgIds) throws Exception {
        List<TreeUtils> tree = orgService.getOrgListByOrgIdUpHasSelf(orgIds);
        return R.ok().put("orgs", tree);
    }

    /**
     * 向上查询直至顶级,不包含自己
     * @param orgIds
     * @return
     */
    @PostMapping("/getOrgListByOrgIdUpHasNoSelf")
    public R getOrgListByOrgIdUpHasNoSelf(@RequestBody String[] orgIds) throws Exception {
        List<TreeUtils> tree = orgService.getOrgListByOrgIdUpHasNoSelf(orgIds);
        return R.ok().put("orgs", tree);
    }
    
    /**
     * 向上查询直至顶级
     * @param orgId 机构id
     * @return OrgHasParent
     */
    @PostMapping("/getOrgListByOrgIdUpHasNoSelfWithTree")
    public OrgHasParent getOrgListByOrgIdUpHasNoSelfWithTree(@RequestBody String orgId) throws Exception {
        return orgService.getOrgListByOrgIdUpHasNoSelfWithTree(orgId);
    }
    
    /**
     * 所有机构分页查询
     * @param params 查询条件{page,limit,dataForm:{orgCode,orgName}}
     * @return
     */
    @PostMapping("/queryAllListIncludeDept")
    public R queryAllListIncludeDept(@RequestBody Map<String, Object> params) {
        PageUtils page = orgService.queryAllListIncludeDept(params);
        return R.ok().put("page", page);
    }

    /**
     * 分页查询全量机构
     * @param params {
     *                   'page': pageIndex,
     *                   'limit': pageSize,
     *                   'orgCode': orgCode,
     *                   'orgName': orgName,
     * 				     'orgRank': orgRank,
     * 				     'orgStatus': orgStatus,
     * 				     'orgType': orgType,
     *                }
     * @return 分页结果
     */
    @PostMapping("/listAdmin")
    @RequiresPermissions("sys:orgAdmin:list")
    public R listAdmin(@RequestBody Map<String, Object> params) {
        PageUtils page = orgService.queryPageAdmin(params);
        return R.ok().put("page", page);
    }

    /**
     * 将删除状态的机构恢复正常
     * @param id 机构ID
     * @return 删除结果
     */
    @GetMapping("/rollbackOrg/{id}")
    @RequiresPermissions("sys:orgAdmin:rollback")
    public R rollbackOrg(@PathVariable("id") String id) {
        try {
            orgService.rollbackOrg(id);
            return R.ok();
        } catch (Exception e) {
            log.error("恢复机构失败", e);
            return R.error("恢复机构失败");
        }
    }

    /**
     * 按参数条件返回机构list
     * @return
     */
    @PostMapping("/getOrgListByCondition")
    public List<Org> getOrgListByCondition(@RequestBody Map<String, Object> params) {
        return orgService.getOrgListByCondition(params);
    }
}
